import { Button, Modal, Space, Row, Col, Image, message, Tag, Badge } from 'antd';
import { CopyOutlined, createFromIconfontCN, EditOutlined } from '@ant-design/icons';
import React, { useState, useRef, useEffect } from 'react';
import { Access, useAccess, history, getDvaApp } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormText,
  ProFormTextArea,
  ProFormSelect,
  ProFormDateTimeRangePicker,
  ProFormTimePicker,
  ProFormDatePicker,
} from '@ant-design/pro-form';
import moment from 'moment';
import $utils from '@/utils/utils';
import { billStatusTypes, deliveryWayData, statusData } from '@/utils/common';
// 订单接口导入
import {
  getDeliveryList,
  changePhone,
  billReturn,
  deliveryCheckout,
  sendSms,
  getDeliveryLog,
  orderToCab,
  cancelReturn,
  getDeliveryTotal,
  delivertOrderExport,
  delivertOrderDownload,
} from '@/services/delivery';
// 驿站接口导入
import { getStationName } from '@/services/postHouse';
// 快递公司接口导入
import { getExpressData } from '@/services/company';
import Pagination from '@/components/Pagination';

const MyIcon = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_3354826_k42a89lunf.js',
});

const initDate = {
  delay: 0, // 是否查询滞留件  0全部，1查询
  timeType: 1, // 1入库时间, 2出库时间。当指定开始和结束时间时，必须指定时间类型
  timeStart: moment().subtract(2, 'days').startOf('day'), //  开始时间
};

const notifyText = [
  {
    label: '发送中',
    value: 3,
  },
  {
    label: '发送成功',
    value: 1,
  },
  {
    label: '发送失败',
    value: 2,
  },
];

// 退回原因
const reasonList = [
  { label: '无人接听', value: 1 },
  { label: '拒收件', value: 2 },
  { label: '错分件', value: 3 },
  { label: '改地址', value: 4 },
  { label: '逾期件', value: 5 },
  { label: '遗失件', value: 6 },
  { label: '破损件', value: 7 },
  { label: '非手机号', value: 8 },
  { label: '快递公司追回', value: 9 },
  { label: '停机关机', value: 10 },
  { label: '家属区', value: 11 },
  { label: '自取', value: 12 },
  { label: '转寄', value: 13 },
  { label: '其它', value: 14 },
];

const storageTypes = [
  { label: '货架', value: 1 },
  { label: '柜体', value: 3 },
  { label: '暂存区', value: 4 },
];

const delayTypes = [
  { label: '全部', value: 0 },
  { label: '是', value: 1 },
];

const DeliveryList: React.FC = () => {
  // 解决无法调用dispatch
  const dispatch = getDvaApp()._store.dispatch;
  // 获取权限
  const access = useAccess();
  const formRef = useRef<ProFormInstance>();
  const orderExportFormRef = useRef<ProFormInstance>();
  const orderDownloadFormRef = useRef<ProFormInstance>();
  const actionRef = useRef<ActionType>();

  const [initParams, setParams] = useState<any>();
  const [rotation, handleUpdRotation] = useState<number>(0);
  // const [img_zoom, handleUpdZoom] = useState<number>(100);
  const [img_zoom] = useState<number>(100);
  const [current, setCurrent] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(20);
  const [total, setTotal] = useState<number>(0);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [collapsed, setCollapsed] = useState<boolean>(false);

  // table列表内容滚动区域的高度
  const [scrollY, setScrollY] = useState<number>();

  // 标记退回弹窗
  const [backModalVisible, handleBackModalVisible] = useState<boolean>(false);
  // 导出订单
  const [orderExportVisible, handleOrderExportVisible] = useState<boolean>(false);
  // 打印接驳单
  const [downloadVisible, handleDownloadVisible] = useState<boolean>(false);
  // 出库弹窗
  const [deliveryModalVisible, handleDeliveryModalVisible] = useState<boolean>(false);
  // 柜体退回弹窗
  const [cabReturnModalVisible, handleCabReturnModalVisible] = useState<boolean>(false);
  // 修改手机号弹窗
  const [updPhoneVisible, handleUpdPhoneVisible] = useState<boolean>(false);

  const [currentData, setCurrentData] = useState<any>();

  const [expressList, setExpressList] = useState<API.Select[]>([]);
  const [stationNames, setStationNames] = useState<API.Select[]>([]);

  const l_state: any = history.location.state;

  const getScrollY = () => {
    // 计算并设置table内容区域高度
    const windowHeight = document.documentElement.clientHeight;
    const clientTop = document.getElementsByClassName('zkfc-table')[0]?.getBoundingClientRect().top;
    setScrollY(windowHeight - clientTop - 130);
  };

  useEffect(() => {
    if (!initParams) {
      const data = l_state
        ? {
            ...l_state,
            dateTime: [moment(l_state?.timeStart) || initDate.timeStart],
          }
        : {
            ...initDate,
            dateTime: [initDate.timeStart],
          };
      l_state?.timeEnd && (data.dateTime[1] = moment(l_state?.timeEnd));
      setParams(data);
    }
  }, []);

  // 筛选重置时更新表单
  useEffect(() => {
    getScrollY();

    const data = {
      ...initDate,
      dateTime: [initDate.timeStart],
    };
    if (JSON.stringify(data) === JSON.stringify(initParams)) {
      formRef && formRef.current?.resetFields();
      actionRef?.current?.reset && actionRef?.current?.reset();
    }
  }, [initParams]);

  // 快递公司列表
  useEffect(() => {
    const getOptions = async () => {
      let result = $utils.getStorage('express_options');
      !result && (result = await getExpressData());
      setExpressList(result);
    };
    getOptions();
  }, []);

  useEffect(() => {
    const getStationNames = async () => {
      try {
        const msg = await getStationName({ name: '' });
        let new_data: API.Select[] = [];
        if (msg.code === 0) {
          msg.body.map((item: { id: number; name: string }) => {
            new_data.push({
              label: item.name,
              value: item.id,
            });
          });
          setStationNames(new_data);
          return;
        }
      } catch (error) {
        console.log(error);
        message.error('驿站名称列表获取失败!');
      }
    };

    getStationNames();
  }, []);

  const disabledTaskDate = (current: any, num: number = 90) => {
    // 只可选择90天内，上线日期后
    return !(
      current > moment('06-14-2022', 'MM-DD-YYYY').endOf('days') &&
      current > moment().subtract(num, 'days') &&
      current < moment().subtract(0, 'days').endOf('days')
    );
  };

  // 重发短信确认窗口
  const confirm = (id: string) => {
    Modal.confirm({
      className: 'again-send',
      icon: false,
      width: '320px',
      title: <div style={{ textAlign: 'center', fontSize: 18, color: '#000' }}>重发短信</div>,
      content: (
        <div>
          <div
            style={{
              textAlign: 'center',
              color: 'rgba(136, 136, 136, 100)',
              fontSize: 15,
              marginBottom: 12,
            }}
          >
            确定重发短信通知？
          </div>
          {/* <div>重发短信时，无论收件人手机是否关注微信，都只发短信。</div> */}
        </div>
      ),
      centered: true,
      maskClosable: true,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        // 重发短信逻辑
        const msg = await sendSms({ id });
        if (msg.code === 0) {
          message.success(msg.msg);
          actionRef.current?.reload();
        }
      },
    });
  };

  // 取消退回确认弹窗
  const cancelReturn_confirm = (id: string) => {
    Modal.confirm({
      className: 'again-send',
      icon: false,
      width: '320px',
      title: <div style={{ textAlign: 'center', fontSize: 18, color: '#000' }}>取消退回</div>,
      content: (
        <div>
          <div
            style={{
              textAlign: 'center',
              color: 'rgba(136, 136, 136, 100)',
              fontSize: 15,
              marginBottom: 12,
            }}
          >
            确定取消退回该订单
          </div>
        </div>
      ),
      centered: true,
      maskClosable: true,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        // 重发短信逻辑
        const msg = await cancelReturn({ id });
        if (msg.code === 0) {
          message.success('操作成功');
          setCurrentData(null);
          actionRef.current?.reload();
        }
      },
    });
  };

  // 货架待退回订单 退回操作确认框
  const confirmBack = (id: string) => {
    Modal.confirm({
      className: 'again-send',
      icon: false,
      width: '320px',
      title: <div style={{ textAlign: 'center', fontSize: 18, color: '#000' }}>退回</div>,
      content: (
        <div>
          <div
            style={{
              textAlign: 'center',
              color: 'rgba(136, 136, 136, 100)',
              fontSize: 15,
              marginBottom: 12,
            }}
          >
            确定退回该订单？
          </div>
        </div>
      ),
      centered: true,
      maskClosable: true,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const params = {
          id: id,
          open: 0,
        };
        const msg = await billReturn(params);
        if (msg.code === 0) {
          message.success('操作成功');
          setCurrentData(null);
          actionRef.current?.reload();
        }
      },
    });
  };

  // 重发柜体确认窗口
  const cab_confirm = (id: string) => {
    Modal.confirm({
      className: 'again-send',
      icon: false,
      width: '320px',
      title: <div style={{ textAlign: 'center', fontSize: 18, color: '#000' }}>重发柜体</div>,
      content: (
        <div>
          <div
            style={{
              textAlign: 'center',
              color: 'rgba(136, 136, 136, 100)',
              fontSize: 15,
              marginBottom: 12,
            }}
          >
            确定将订单重发柜体？确定后请关注订单状态是否为变待出库
          </div>
        </div>
      ),
      centered: true,
      maskClosable: true,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        // 重发短信逻辑
        const msg = await orderToCab({ orderId: id });
        if (msg.code === 0) {
          message.success('操作成功');
          actionRef.current?.reload();
        }
      },
    });
  };

  // 查看手机号
  const inspectPhone = (data: any) => {
    Modal.info({
      className: 'inspect-phone',
      icon: false,
      maskClosable: true,
      closable: true,
      content: (
        <div style={{ textAlign: 'center', fontSize: 28, color: '#000' }}>
          <p>
            {data?.receiver?.phone.substring(0, 3)} {data?.receiver?.phone.substring(3, 7)}{' '}
            {data?.receiver?.phone.substring(7, 11)}
          </p>
          <p>{data?.receiver?.name}</p>
          <p>{data?.expressName}</p>
        </div>
      ),
      onOk() {},
    });
  };

  // 手机扫描模式无
  const getDetailLogImg = async (id: any) => {
    let data = null;
    try {
      const msg = await getDeliveryLog({ id });
      const item = msg.body.find((item: any) => item.op === '入库');
      const explainData = item.explain.split('|');
      if (explainData[1].indexOf('http') > -1) {
        data = explainData[1].substring(explainData[1].indexOf('http'));
      }
    } catch (error) {
      console.log(error);
    }
    return data;
  };

  const columns: ProColumns<any>[] = [
    {
      title: '时间类型',
      dataIndex: 'timeType',
      hideInTable: true,
      valueType: 'select',
      order: 9,
      fieldProps: {
        options: [
          { label: '入库时间', value: 1 },
          { label: '出库时间', value: 2 },
        ],
      },
    },
    {
      title: '起止时间',
      dataIndex: 'dateTime',
      hideInTable: true,
      valueType: 'dateTimeRange',
      order: 8,
      colSize: collapsed ? 1 : 2,
      search: {
        transform: (value: any) => ({ timeStart: value[0], timeEnd: value[1] }),
      },
      fieldProps: {
        disabledDate: (current: any) => disabledTaskDate(current),
        ranges: {
          今天: [moment().startOf('day'), moment().endOf('day')],
          昨天: [
            moment().subtract(1, 'days').startOf('day'),
            moment().subtract(1, 'days').endOf('day'),
          ],
          本周: [moment().startOf('week'), moment().endOf('week')],
          本月: [moment().startOf('month'), moment().endOf('month')],
          上月: [
            moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
            moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
          ],
        },
      },
    },
    {
      title: '运单号',
      dataIndex: 'expCode',
      order: 10,
      // tip: 'The rule name is the unique key',
      width: 200,
      fieldProps: {
        maxLength: 30,
      },
      search: {
        transform: (value: any) => ({ expCode: value.replace(/\s*/g, '') }),
      },
      render: (dom, entity) => {
        const handleJump = () => {
          const newTab = {
            name: `查看${entity.expCode}`,
            path: `/order/delivery/list/detail`,
            state: {
              status: 'detail',
              data: entity,
            },
          };
          // 设置当前tab对象
          $utils.setNewTab(dispatch, newTab);
          $utils.addTab(dispatch, newTab);
          history.push({
            pathname: `/order/delivery/list/detail`,
            state: {
              status: 'detail',
              data: entity,
            },
          });
        };
        return (
          <>
            {entity?.status.detained ? (
              <Badge.Ribbon
                style={{ left: '-14px', top: '-16px' }}
                color={'volcano'}
                placement="start"
                text="滞留件"
              >
                <div
                  key={entity.id}
                  style={{ cursor: 'pointer' }}
                  onClick={() => {
                    handleJump();
                  }}
                >
                  <div style={{ paddingTop: '6px' }}>
                    {dom}
                    <Button
                      type="link"
                      icon={<CopyOutlined />}
                      onClick={(e) => {
                        e.stopPropagation();
                        e.nativeEvent.stopImmediatePropagation();
                        $utils.copyCot(entity.expCode);
                      }}
                    />
                  </div>
                  <div>{entity.expressName}</div>
                </div>
              </Badge.Ribbon>
            ) : (
              <div
                key={entity.id}
                style={{ cursor: 'pointer' }}
                onClick={() => {
                  handleJump();
                }}
              >
                <div style={{ paddingTop: '6px' }}>
                  {dom}
                  <Button
                    type="link"
                    icon={<CopyOutlined />}
                    onClick={(e) => {
                      e.stopPropagation();
                      e.nativeEvent.stopImmediatePropagation();
                      $utils.copyCot(entity.expCode);
                    }}
                  />
                </div>
                <div>{entity.expressName}</div>
              </div>
            )}
          </>
        );
      },
    },
    {
      title: '收件人手机',
      dataIndex: 'receiverPhone',
      hideInTable: true,
      order: 7,
      fieldProps: {
        maxLength: 25,
      },
      search: {
        transform: (value: any) => ({ receiverPhone: value.replace(/\s*/g, '') }),
      },
    },
    {
      title: '驿站名称',
      dataIndex: 'stationName',
      valueType: 'select',
      width: 160,
      order: 3,
      search: {
        transform: (value: any) => ({ stationId: value }),
      },
      fieldProps: {
        showSearch: true,
        options: stationNames,
        placeholder: '请输入内容',
      },
    },
    {
      title: '投递人手机',
      dataIndex: 'deliverPhone',
      hideInTable: true,
      order: 3,
      fieldProps: {
        maxLength: 11,
      },
    },
    {
      title: '取件码',
      dataIndex: 'pickupCode',
      valueType: 'textarea',
      width: 160,
      render: (dom, entity) => {
        const storeModeData = storageTypes.find((item: any) => item.value === entity.storeMode);
        return (
          <div key={entity.id}>
            <div style={{ fontWeight: 'bold' }}>
              {dom}({entity.storeMode === 2 ? '货架' : storeModeData?.label})
            </div>
            <div>{entity?.checkinTime}</div>
          </div>
        );
      },
    },
    {
      title: '存放位置',
      dataIndex: 'addr',
      valueType: 'textarea',
      width: 160,
      search: false,
    },
    {
      title: '存储类型',
      dataIndex: 'storeMode',
      valueType: 'select',
      order: 2,
      search: {
        transform: (value: any) => ({ storageType: value }),
      },
      width: 80,
      fieldProps: {
        options: storageTypes,
        placeholder: '全部',
      },
      hideInTable: true,
      render: (dom, entity) => {
        return entity.storeMode < 3 ? <div>货架</div> : <div>{dom}</div>;
      },
    },
    {
      title: '是否滞留件',
      dataIndex: 'delay',
      hideInTable: true,
      valueType: 'select',
      order: 1,
      fieldProps: {
        options: delayTypes,
      },
    },
    {
      title: '柜体编码',
      dataIndex: 'cabCode',
      hideInTable: true,
      search: {
        transform: (value: any) => ({ cabCode: value.replace(/\s*/g, '') }),
      },
      fieldProps: {
        maxLength: 30,
        controls: false,
      },
    },
    {
      title: '收件人',
      dataIndex: 'receiver',
      // sorter: true,
      search: false,
      hideInForm: true,
      width: 120,
      render: (dom, entity) => {
        const phone = entity?.receiver?.phone
          ? entity?.receiver?.phone.slice(0, 3) + '****' + entity?.receiver?.phone.slice(-4)
          : '';
        const canChange = [1, 2].includes(entity?.status.bill);
        return (
          <div key={entity.id}>
            <div
              onClick={() => {
                entity?.receiver?.phone && inspectPhone(entity);
              }}
            >
              {entity?.receiver?.name ? entity?.receiver?.name.slice(0, 1) + '**' : ''}
            </div>
            {
              <div
                onClick={() => {
                  entity?.receiver?.phone && inspectPhone(entity);
                }}
              >
                {entity?.receiver?.phone ? phone : '--'}
                <Access accessible={access.can_deliveryAll.changePhone}>
                  {canChange && (
                    <EditOutlined
                      onClick={async (e) => {
                        e.stopPropagation();
                        e.nativeEvent.stopImmediatePropagation();
                        // 修改手机号弹窗
                        setCurrentData(entity);
                        if (entity.checkinMode === 1) {
                          const img = await getDetailLogImg(entity.id);
                          img && Object.assign(entity, { scanImg: img });
                        }
                        handleUpdPhoneVisible(true);
                      }}
                    />
                  )}
                </Access>
              </div>
            }
            {entity?.status?.blacklist && entity?.status.bill === 1 && (
              <div>
                <Tag color="#f50">黑名单用户</Tag>
              </div>
            )}
            {!entity?.receiver?.phone && entity?.checkinMode === 2 && (
              <div>
                {entity?.status?.ocr === 3 && (
                  <div style={{ color: 'red', fontWeight: 'bold' }}>OCR识别失败</div>
                )}
                {entity?.status?.ocr === 1 && <div style={{ fontWeight: 'bold' }}>OCR识别中</div>}
              </div>
            )}
          </div>
        );
      },
    },
    {
      title: '投递类型',
      align: 'center',
      dataIndex: 'deliveryWay',
      valueType: 'select',
      search: false,
      width: 80,
      fieldProps: {
        options: deliveryWayData,
      },
    },
    {
      title: '订单状态',
      dataIndex: 'billState',
      hideInForm: true,
      order: 6,
      width: 170,
      valueType: 'select',
      fieldProps: {
        placeholder: '全部订单状态',
        options: billStatusTypes,
      },
      render: (dom, entity) => {
        return (
          <div key={entity.id}>
            <div>{statusData[entity.status.bill - 1]}</div>
            <div>
              {/* 待出库 、待核对手机号 才显示按钮，否则显示时间 */}
              {[1, 2, 5, 6, 7].includes(entity.status.bill) ? (
                <Space>
                  <Access accessible={access.can_deliveryAll.backUp}>
                    <Button
                      type="primary"
                      size={'small'}
                      onClick={() => {
                        setCurrentData(entity);
                        handleDeliveryModalVisible(true);
                      }}
                    >
                      点此出库
                    </Button>
                  </Access>

                  {
                    <Access accessible={access.can_deliveryAll.return}>
                      <Button
                        type="primary"
                        size={'small'}
                        onClick={() => {
                          // 先判断待退回，再判断是否柜体，不同退回弹窗
                          setCurrentData(entity);
                          if (entity.status.bill === 6) {
                            entity.storeMode === 3
                              ? handleCabReturnModalVisible(true)
                              : confirmBack(entity.id);
                          } else {
                            handleBackModalVisible(true);
                          }
                        }}
                      >
                        {entity.status.bill !== 6 ? '标记退回' : '点此退回'}
                      </Button>
                    </Access>
                  }
                </Space>
              ) : (
                <div>{entity.status.bill == 3 ? entity.checkoutTime : entity.returnTime}</div>
              )}
            </div>
          </div>
        );
      },
    },
    {
      title: '通知状态',
      // sorter: true,
      dataIndex: 'notifyState',
      order: 4,
      valueType: 'select',
      width: 100,
      fieldProps: {
        placeholder: '全部通知状态',
        options: notifyText,
      },
      render: (dom, entity) => {
        const item = notifyText.find((i) => i.value === entity.status.notify);
        return (
          <div key={entity.id}>
            {entity.status.notify > 0 && item?.value ? (
              <div
                style={{
                  color: [1].includes(item?.value)
                    ? 'green'
                    : [2].includes(item?.value)
                    ? 'red'
                    : '#333',
                }}
              >
                {item?.label}
              </div>
            ) : (
              <div>--</div>
            )}
          </div>
        );
      },
    },
    {
      title: '快递公司',
      dataIndex: 'expressId',
      hideInTable: true,
      valueType: 'select',
      order: 5,
      fieldProps: {
        showSearch: true,
        options: expressList,
        placeholder: '全部快递公司',
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: '150px',
      fixed: 'right',
      render: (_, record) => [
        <div key={record.id}>
          {record?.status.bill === 2 && (
            <Access accessible={access.can_deliveryAll.sendSms} fallback={'--'}>
              <Button
                type="primary"
                size="small"
                onClick={() => {
                  confirm(record.id);
                }}
              >
                重发短信
              </Button>
            </Access>
          )}
          {record?.status.bill === 5 && (
            <Access accessible={access.can_deliveryAll.sendCab} fallback={'--'}>
              <Button
                type="primary"
                size="small"
                onClick={() => {
                  cab_confirm(record.id);
                }}
              >
                重发柜体
              </Button>
            </Access>
          )}
          {record?.status.bill === 6 && (
            <Button
              type="primary"
              size="small"
              onClick={() => {
                cancelReturn_confirm(record.id);
              }}
            >
              取消退回
            </Button>
          )}
          {![2, 5, 6].includes(record?.status.bill) && <div>--</div>}
        </div>,
      ],
    },
  ];

  // 获取总数展示
  const handleShowCount = async () => {
    const msg = await getDeliveryTotal(initParams);
    if (msg.code === 0) {
      setTotal(msg.body);
    }
  };

  // 切换上下页
  const onSelectChange = (type: string) => {
    if (type === 'prev') {
      setCurrent(current - 1);
    } else if (type === 'next') {
      setCurrent(current + 1);
    }
  };

  // 切换每页展示数目
  const onShowSizeChange = (pSize: number) => {
    setPageSize(pSize);
  };

  return (
    <PageContainer>
      {initParams && (
        <ProTable<API.RuleListItem, API.PageParams>
          actionRef={actionRef}
          formRef={formRef}
          rowKey="id"
          tableClassName="zkfc-table"
          scroll={{
            y: scrollY || 0,
          }}
          pagination={false}
          form={{
            initialValues: initParams,
          }}
          title={() => [
            <div key="index">
              <Button type="primary" onClick={() => handleOrderExportVisible(true)}>
                导出
              </Button>{' '}
              &nbsp;&nbsp;&nbsp;&nbsp;
              <Button
                type="primary"
                onClick={() => {
                  const newTab = {
                    name: '查看历史订单',
                    path: '/order/delivery/history',
                    state: {
                      status: 'historyList',
                      data: {},
                    },
                  };
                  // 设置当前tab对象
                  $utils.setNewTab(dispatch, newTab);
                  $utils.addTab(dispatch, newTab);
                  history.push({
                    pathname: `/order/delivery/history`,
                    state: {
                      status: 'historyList',
                      data: {},
                    },
                  });
                }}
              >
                查看历史订单
              </Button>
              {/* &nbsp;&nbsp;&nbsp;&nbsp;
              <Button type="primary" onClick={() => handleDownloadVisible(true)}>
                打印接驳单
              </Button> */}
            </div>,
          ]}
          search={
            access.can_deliveryAll.search
              ? {
                  labelWidth: 80,
                  collapsed: collapsed,
                  onCollapse: (collapsed: boolean) => {
                    setCollapsed(collapsed);
                    getScrollY();
                    actionRef?.current?.reload && actionRef?.current?.reload();
                  },
                  // collapseRender: () => false,
                  // className: 'zkfc-ceiling',
                  span: 6,
                  optionRender: (searchConfig, formProps, dom) => [
                    dom.reverse()[0],
                    <Button
                      key="resetText"
                      onClick={() => {
                        const data = {
                          ...initDate,
                          dateTime: [initDate.timeStart],
                        };
                        setParams(data);
                      }}
                    >
                      重置
                    </Button>,
                  ],
                }
              : false
          }
          toolBarRender={false}
          options={false}
          footer={() => {
            return (
              <Pagination
                current={current}
                pageSize={pageSize}
                total={total}
                length={dataSource.length}
                showCount={handleShowCount}
                onChange={onSelectChange}
                onShowSizeChange={onShowSizeChange}
              />
            );
          }}
          params={{ current, pageSize }}
          // @ts-nocheck
          // @ts-ignore
          request={async (params) => {
            if (!params.timeType) {
              params.timeType = initDate.timeType;
            }
            if (!params.timeStart) {
              params.timeStart = initDate.timeStart.format('YYYY-MM-DD HH:mm:ss');
            }
            if (!!params.pickupCode && !params.stationId) {
              message.warning('按取件码维度搜索时，必须选择驿站名称');
              delete params.pickupCode;
              return;
            }
            const msg = await getDeliveryList(params);
            // 将筛选条件存进 tabs
            if (msg.code === 0) {
              $utils.addTab(dispatch, {
                name: '派件业务',
                path: '/order/delivery/list',
                isTopMenu: true,
                state: params,
              });
              setParams(params);
              setTotal(0);
              setDataSource(msg.body || []);
            }
            return {
              data: msg.body || [],
              success: msg.code === 0,
              // 不传会使用 data 的长度，如果是分页一定要传
              // total: msg.body?.count,
            };
          }}
          columns={columns}
        />
      )}
      <ModalForm
        title={'修改手机号'}
        modalProps={{
          centered: true,
          destroyOnClose: true,
          open: updPhoneVisible,
          onCancel: () => {
            setCurrentData(null);
            handleUpdPhoneVisible(false);
          },
        }}
        width="950px"
        labelCol={{ span: 6 }}
        initialValues={{
          ...currentData,
          old_phone: currentData?.receiver.phone || '--',
        }}
        layout={'horizontal'}
        onFinish={async (value) => {
          const params = {
            id: currentData.id,
            phone: value.phone,
          };
          const msg = await changePhone(params);
          if (msg.code === 0) {
            message.success('修改成功!');
            setCurrentData(null);
            actionRef.current?.reload();
            handleUpdPhoneVisible(false);
          }
        }}
      >
        <Row gutter={16}>
          <Col
            span={12}
            style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center' }}
          >
            <ProFormText
              label="运单号"
              disabled
              rules={[
                {
                  required: true,
                },
              ]}
              width="md"
              name="expCode"
            />
            <ProFormText
              label="入库时间"
              disabled
              rules={[
                {
                  required: true,
                },
              ]}
              width="md"
              name="checkinTime"
            />
            <ProFormText
              label="原手机号"
              disabled
              rules={[
                {
                  required: true,
                },
              ]}
              width="md"
              name="old_phone"
            />
            <ProFormText
              label="新手机号"
              placeholder={'请输入新的客户手机号'}
              rules={[
                { required: true },
                { len: 11, message: '请输入11位手机号' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (value && getFieldValue('old_phone') === value) {
                      return Promise.reject(new Error('新手机号不能与原手机号相同'));
                    }
                    return Promise.resolve();
                  },
                }),
              ]}
              width="md"
              name="phone"
            />
            <div
              style={{
                fontSize: 12,
                color: 'rgba(16, 16, 16, 100)',
                marginTop: 42,
                textAlign: 'center',
              }}
            >
              注意：如订单需要支付取件费或延期费，修改手机号后将重新计费！
            </div>
          </Col>
          <Col span={12} style={{ display: 'flex', alignItems: 'center', flexDirection: 'column' }}>
            <div
              style={{
                width: '100%',
                padding: '10px 15%',
                display: 'flex',
                justifyContent: 'space-around',
                alignItems: 'center',
                fontSize: '32px',
                color: '#1890FF',
              }}
            >
              <MyIcon
                type="icon-a-shunshizhenxuanzhuan90"
                onClick={() => {
                  handleUpdRotation(rotation + 90);
                }}
              />
              <MyIcon
                type="icon-a-nishizhenxuanzhuan90"
                onClick={() => {
                  handleUpdRotation(rotation - 90);
                }}
              />
              <MyIcon
                type="icon-a-shunshizhenxuanzhuan180"
                onClick={() => {
                  handleUpdRotation(rotation + 180);
                }}
              />
            </div>
            <div style={{ width: 360, height: 360, overflow: 'hidden' }}>
              {currentData?.ocrImageTimeout ? (
                <div
                  style={{
                    width: '100%',
                    height: '100%',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    backgroundColor: '#E8E8E8',
                  }}
                >
                  图片已过期(保存30天)
                </div>
              ) : currentData?.ocrImage || currentData?.scanImg ? (
                <Image
                  src={currentData?.ocrImage || currentData?.scanImg}
                  style={{
                    width: 360,
                    height: 360,
                    zoom: `${img_zoom}%`,
                    transform: `scale3d(1, 1, 1) rotate(${rotation}deg)`,
                  }}
                  preview={{
                    getContainer: false,
                  }}
                  alt=""
                />
              ) : (
                <div
                  style={{
                    width: '100%',
                    height: '100%',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    backgroundColor: '#E8E8E8',
                  }}
                >
                  该订单为手动输入，无入库底单
                </div>
              )}
            </div>
            {!currentData?.ocrImageTimeout && (currentData?.ocrImage || currentData?.scanImg) && (
              <div style={{ marginTop: 20, width: '100%', padding: '0 12%', display: 'flex' }}>
                <Button
                  type="primary"
                  onClick={() => {
                    $utils.handleDownImage(currentData?.ocrImage || currentData?.scanImg);
                  }}
                >
                  下载图片
                </Button>
              </div>
            )}
          </Col>
        </Row>
      </ModalForm>
      <ModalForm
        title={'退回'}
        modalProps={{
          centered: true,
          open: backModalVisible,
          onCancel: () => {
            handleBackModalVisible(false);
          },
        }}
        width="400px"
        labelCol={{ span: 6 }}
        initialValues={{
          ...currentData,
        }}
        layout={'horizontal'}
        onFinish={async (value) => {
          const params = {
            id: currentData.id,
            reason: value.reason,
            comment: value.comment || '',
          };
          const msg = await billReturn(params);
          if (msg.code === 0) {
            message.success('操作成功');
            setCurrentData(null);
            actionRef.current?.reload();
            handleBackModalVisible(false);
          }
        }}
      >
        <ProFormText
          label="运单号"
          disabled={true}
          width="md"
          name="expCode"
          rules={[
            {
              required: true,
            },
          ]}
        />
        <ProFormText
          label="入库时间"
          width="md"
          disabled={true}
          name="checkinTime"
          rules={[
            {
              required: true,
            },
          ]}
        />
        <ProFormSelect
          width="md"
          name="reason"
          label="退回原因"
          rules={[
            {
              required: true,
            },
          ]}
          fieldProps={{
            options: reasonList,
          }}
        />
        <ProFormTextArea
          label="备注"
          fieldProps={{ maxLength: 50, placeholder: '请输入备注,最多50字' }}
          rules={[{ max: 50 }]}
          width="md"
          name="comment"
        />
      </ModalForm>
      <ModalForm
        title={'出库'}
        modalProps={{
          centered: true,
          open: deliveryModalVisible,
          onCancel: () => {
            handleDeliveryModalVisible(false);
          },
        }}
        width="360px"
        labelCol={{ span: 6 }}
        layout={'horizontal'}
        onFinish={async (value) => {
          const params = {
            id: currentData.id,
            open: value.open - 1,
          };
          const msg = await deliveryCheckout(params);
          if (msg.code === 0) {
            message.success('操作成功');
            setCurrentData(null);
            actionRef.current?.reload();
            handleDeliveryModalVisible(false);
          }
        }}
      >
        <ProFormSelect
          rules={[
            {
              required: true,
            },
          ]}
          fieldProps={{
            options:
              +currentData?.storeMode === 3
                ? [
                    { label: '仅出库', value: 1 },
                    { label: '开箱并出库', value: 2 },
                  ]
                : [{ label: '出库', value: 1 }],
          }}
          width="md"
          name="open"
        />
        <p style={{ textAlign: 'center' }}>提示: 此处出库后，驿站账户将不再获得收入</p>
      </ModalForm>
      <ModalForm
        title={'提示'}
        modalProps={{
          centered: true,
          open: cabReturnModalVisible,
          onCancel: () => {
            handleCabReturnModalVisible(false);
          },
        }}
        width="360px"
        labelCol={{ span: 6 }}
        layout={'horizontal'}
        onFinish={async (value) => {
          const params = {
            id: currentData.id,
            open: value.open,
          };
          const msg = await billReturn(params);
          if (msg.code === 0) {
            message.success('操作成功');
            setCurrentData(null);
            actionRef.current?.reload();
            handleCabReturnModalVisible(false);
          }
        }}
      >
        <ProFormSelect
          rules={[
            {
              required: true,
            },
          ]}
          fieldProps={{
            options: [
              { label: '仅退回', value: 0 },
              { label: '开箱并退回', value: 1 },
            ],
          }}
          width="md"
          name="open"
        />
        <p style={{ textAlign: 'center' }}>退回后，请及时到柜体取出包裹！</p>
      </ModalForm>

      <ModalForm
        title={'导出'}
        modalProps={{
          centered: true,
          open: orderExportVisible,
          onCancel: () => {
            handleOrderExportVisible(false);
          },
        }}
        formRef={orderExportFormRef}
        layout={'horizontal'}
        width="520px"
        onFinish={async (value) => {
          const data = await orderExportFormRef.current?.validateFields();
          if (data) {
            const startTime = data.dateTimeRange[0] ? data.dateTimeRange[0] : '';
            const endTime = data.dateTimeRange[1] ? data.dateTimeRange[1] : '';
            const day = endTime.diff(startTime, 'day');
            if (day > 30) {
              message.error('起止时间最大选择1个月（31天）');
            } else {
              const params = {
                stationId: data.stationId,
                expressId: data.expressId,
                status: data.status,
                startTime: moment(startTime).format('YYYY-MM-DD HH:mm:ss'),
                endTime: moment(endTime).format('YYYY-MM-DD HH:mm:ss'),
              };
              const msg = await delivertOrderExport(params);
              if (msg.code === 0) {
                message.success('操作成功!');
                handleOrderExportVisible(false);
              }
            }
          }
        }}
      >
        <ProFormSelect
          name="stationId"
          label={'驿站名称'}
          rules={[
            {
              required: true,
              message: '请选择驿站名称',
            },
          ]}
          fieldProps={{
            options: stationNames,
            placeholder: '请输入内容',
          }}
        />
        <ProFormSelect
          name="expressId"
          label={'快递公司'}
          rules={[
            {
              required: true,
              message: '请选择快递公司',
            },
          ]}
          fieldProps={{
            options: expressList,
            placeholder: '全部快递公司',
          }}
        />
        <ProFormDateTimeRangePicker
          rules={[
            {
              required: true,
              message: '请选择起止时间',
            },
          ]}
          name={['dateTimeRange']}
          label="起止时间"
          fieldProps={{
            disabledDate: (current: any) => disabledTaskDate(current),
            ranges: {
              今天: [moment().startOf('day'), moment().endOf('day')],
              昨天: [
                moment().subtract(1, 'days').startOf('day'),
                moment().subtract(1, 'days').endOf('day'),
              ],
              // 本周: [moment().startOf('week'), moment().endOf('week')],
              // 本月: [moment().startOf('month'), moment().endOf('month')],
              上月: [
                moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
              ],
            },
          }}
        />

        <ProFormSelect
          name="status"
          label={'订单状态'}
          rules={[
            {
              required: true,
              message: '请选择订单状态',
            },
          ]}
          initialValue={0}
          fieldProps={{
            options: [{ label: '全部订单状态', value: 0 }].concat(billStatusTypes),
            placeholder: '全部订单状态',
          }}
        />
        <div style={{ color: 'red' }}>
          注：起止时间最大选择1个月（31天），最大支持1年内订单（12个月）
        </div>
      </ModalForm>
      <ModalForm
        title={'打印接驳单'}
        modalProps={{
          centered: true,
          onCancel: () => {
            handleDownloadVisible(false);
          },
        }}
        formRef={orderDownloadFormRef}
        visible={downloadVisible}
        width="520px"
        layout={'horizontal'}
        onFinish={async (value) => {
          const data = await orderDownloadFormRef.current?.validateFields();
          if (data) {
            const date = data?.dateTime
              ? moment(data.dateTime).format('YYYY-MM-DD')
              : moment().format('YYYY-MM-DD');
            const startTime = data?.timeRange[0]
              ? moment(data.timeRange[0]).format('HH:mm:ss')
              : moment().format('HH:mm:ss');
            const endTime = data?.timeRange[1]
              ? moment(data.timeRange[1]).format('HH:mm:ss')
              : moment().format('HH:mm:ss');
            const params = {
              stationId: data?.stationId,
              expressId: data?.expressId,
              status: data?.status,
              startTime: `${date} ${startTime}`,
              endTime: `${date} ${endTime}`,
            };
            console.log('paramsparamsparams', params);
            const msg = await delivertOrderDownload(params);
            if (msg.code === 0) {
              message.success('操作成功!');
              handleDownloadVisible(false);
            }
          }
        }}
      >
        <ProFormSelect
          name="stationId"
          label={'驿站名称'}
          rules={[
            {
              required: true,
              message: '请选择驿站名称',
            },
          ]}
          fieldProps={{
            options: stationNames,
            placeholder: '请输入内容',
          }}
        />
        <ProFormSelect
          name="expressId"
          label={'快递公司'}
          rules={[
            {
              required: true,
              message: '请选择快递公司',
            },
          ]}
          fieldProps={{
            options: expressList,
            placeholder: '全部快递公司',
          }}
        />
        <ProFormDatePicker
          rules={[
            {
              required: true,
              message: '请选择入库时间',
            },
          ]}
          width={390}
          name="dateTime"
          label="入库时间"
          fieldProps={{
            disabledDate: (current: any) => disabledTaskDate(current),
          }}
        />

        <ProFormTimePicker.RangePicker
          rules={[
            {
              required: true,
              message: '请选择时间范围',
            },
          ]}
          width={390}
          name={['timeRange']}
          label="时间范围"
        />

        <ProFormSelect
          name="status"
          label={'订单状态'}
          rules={[
            {
              required: true,
              message: '请选择订单状态',
            },
          ]}
          initialValue={0}
          fieldProps={{
            options: [{ label: '全部订单状态', value: 0 }].concat(billStatusTypes),
            placeholder: '全部订单状态',
          }}
        />
        <div style={{ color: 'red' }}>注：入库时间仅可选择近90天内任意一天</div>
      </ModalForm>
    </PageContainer>
  );
};

export default DeliveryList;
